import React from 'react';
import { Card, Row, Col, Form, DatePicker, Button, Table, Space, Typography, Select, Tag, Radio, Input } from 'antd';
import { AlertOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
// 统一封装的 ECharts 引入
import echarts from '../../utils/echarts';

const { RangePicker } = DatePicker;
const { Text } = Typography;

function seededRandom(seed) {
  let x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
}

function formatCSV(rows) {
  const headers = Object.keys(rows[0] || {});
  const escape = (v) => `"${String(v ?? '').replace(/"/g, '""')}"`;
  const lines = [headers.join(',')].concat(rows.map(r => headers.map(h => escape(r[h])).join(',')));
  return lines.join('\n');
}

export default function WarnStatistics() {
  const [form] = Form.useForm();
  const pieRef = React.useRef(null);
  const lineRef = React.useRef(null);
  const barRef = React.useRef(null);
  const pieChart = React.useRef(null);
  const lineChart = React.useRef(null);
  const barChart = React.useRef(null);

  const machines = React.useMemo(() => (
    [ 'M001', 'M002', 'M003', 'M004', 'M005', 'M006' ].map((no, idx) => ({ no, name: `设备${idx+1}` }))
  ), []);
  const types = ['离线', '缺货', '温度异常', '门未关', '支付失败'];
  const levels = ['高', '中', '低'];

  const [filters, setFilters] = React.useState({
    range: [dayjs().subtract(6, 'day'), dayjs()],
    type: undefined,
    level: undefined,
    machineNo: undefined,
  });

  const [tableData, setTableData] = React.useState([]);

  const dateLabels = React.useMemo(() => {
    const start = filters.range?.[0] || dayjs().subtract(6, 'day');
    const end = filters.range?.[1] || dayjs();
    const days = end.diff(start, 'day') + 1;
    return Array.from({ length: days }, (_, i) => start.add(i, 'day').format('YYYY-MM-DD'));
  }, [filters.range]);

  const genAlarms = React.useCallback(() => {
    const rows = [];
    dateLabels.forEach((d, idx) => {
      machines.forEach((m, j) => {
        const count = Math.floor(seededRandom(idx * 13 + j * 17) * 3);
        for (let k = 0; k < count; k++) {
          const tIdx = Math.floor(seededRandom(idx * 31 + j * 7 + k) * types.length);
          const lIdx = Math.floor(seededRandom(idx * 19 + j * 11 + k) * levels.length);
          rows.push({
            time: `${d} ${String(8 + k).padStart(2, '0')}:00:00`,
            equipmentNo: m.no,
            equipmentName: m.name,
            type: types[tIdx],
            level: levels[lIdx],
            message: `${types[tIdx]}告警，级别${levels[lIdx]}`,
          });
        }
      });
    });
    return rows;
  }, [dateLabels, machines]);

  const refreshData = React.useCallback(() => {
    let rows = genAlarms();
    if (filters.type) rows = rows.filter(r => r.type === filters.type);
    if (filters.level) rows = rows.filter(r => r.level === filters.level);
    if (filters.machineNo) rows = rows.filter(r => r.equipmentNo === filters.machineNo);
    setTableData(rows);

    const countByDate = dateLabels.map(d => rows.filter(r => r.time.startsWith(d)).length);
    const countByType = types.map(t => ({ name: t, value: rows.filter(r => r.type === t).length }));
    const topMachines = [...machines].map(m => ({ name: m.name, value: rows.filter(r => r.equipmentNo === m.no).length }))
      .sort((a, b) => b.value - a.value).slice(0, 6);

    if (lineRef.current) {
      if (!lineChart.current) lineChart.current = echarts.init(lineRef.current);
      lineChart.current.setOption({
        title: { text: '告警趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: 40, right: 24, top: 56, bottom: 36 },
        xAxis: { type: 'category', data: dateLabels },
        yAxis: { type: 'value' },
        series: [{ type: 'line', smooth: true, data: countByDate }],
      }, { notMerge: true });
      lineChart.current.resize();
    }
    if (pieRef.current) {
      if (!pieChart.current) pieChart.current = echarts.init(pieRef.current);
      pieChart.current.setOption({
        title: { text: '告警类型占比', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { bottom: 0 },
        series: [{ type: 'pie', radius: '50%', data: countByType }],
      }, { notMerge: true });
      pieChart.current.resize();
    }
    if (barRef.current) {
      if (!barChart.current) barChart.current = echarts.init(barRef.current);
      barChart.current.setOption({
        title: { text: '设备告警排行', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: 40, right: 24, top: 56, bottom: 36 },
        xAxis: { type: 'category', data: topMachines.map(i => i.name) },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: topMachines.map(i => i.value) }],
      }, { notMerge: true });
      barChart.current.resize();
    }
  }, [dateLabels, filters, genAlarms, machines]);

  React.useEffect(() => {
    refreshData();
  }, [refreshData]);

  React.useEffect(() => {
    const onResize = () => {
      pieChart.current?.resize();
      lineChart.current?.resize();
      barChart.current?.resize();
    };
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
      pieChart.current?.dispose();
      lineChart.current?.dispose();
      barChart.current?.dispose();
    };
  }, []);

  const onSearch = () => {
    const v = form.getFieldsValue();
    setFilters(prev => ({
      ...prev,
      range: v.range,
      type: v.type,
      level: v.level,
      machineNo: v.machineNo,
    }));
  };

  const onReset = () => {
    form.resetFields();
    setFilters({ range: [dayjs().subtract(6, 'day'), dayjs()], type: undefined, level: undefined, machineNo: undefined });
  };

  const exportCSV = () => {
    if (!tableData.length) return;
    const csv = formatCSV(tableData.map(r => ({
      时间: r.time,
      设备编号: r.equipmentNo,
      设备名称: r.equipmentName,
      告警类型: r.type,
      告警级别: r.level,
      描述: r.message,
    })));
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `告警统计_${dayjs().format('YYYYMMDD_HHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const levelColor = (lvl) => ({ 高: 'red', 中: 'gold', 低: 'green' }[lvl] || 'blue');

  const columns = [
    { title: '时间', dataIndex: 'time', key: 'time' },
    { title: '设备编号', dataIndex: 'equipmentNo', key: 'equipmentNo' },
    { title: '设备名称', dataIndex: 'equipmentName', key: 'equipmentName' },
    { title: '告警类型', dataIndex: 'type', key: 'type' },
    { title: '告警级别', dataIndex: 'level', key: 'level', render: (lvl) => <Tag color={levelColor(lvl)}>{lvl}</Tag> },
    { title: '描述', dataIndex: 'message', key: 'message' },
  ];

  return (
    <Card
      title={
        <Space align="center">
          <AlertOutlined style={{ color: '#f5222d', fontSize: 18 }} />
          <Text strong>告警统计</Text>
        </Space>
      }
    >
      <Form form={form} layout="inline" initialValues={filters} style={{ marginBottom: 12 }}>
        <Form.Item label="时间范围" name="range">
          <RangePicker allowClear={false} />
        </Form.Item>
        <Form.Item label="告警类型" name="type">
          <Select allowClear style={{ width: 140 }} placeholder="选择类型" options={types.map(t => ({ label: t, value: t }))} />
        </Form.Item>
        <Form.Item label="告警级别" name="level">
          <Radio.Group>
            <Radio.Button value="高">高</Radio.Button>
            <Radio.Button value="中">中</Radio.Button>
            <Radio.Button value="低">低</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="设备" name="machineNo">
          <Select allowClear style={{ width: 160 }} placeholder="选择设备" options={machines.map(m => ({ label: `${m.name}(${m.no})`, value: m.no }))} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>查询</Button>
            <Button onClick={onReset}>重置</Button>
            <Button onClick={exportCSV}>导出CSV</Button>
          </Space>
        </Form.Item>
      </Form>

      <Row gutter={[12, 12]}>
        <Col xs={24} lg={12}>
          <Card size="small" title="告警趋势">
            <div ref={lineRef} style={{ height: 280 }} />
          </Card>
        </Col>
        <Col xs={24} lg={6}>
          <Card size="small" title="告警类型占比">
            <div ref={pieRef} style={{ height: 280 }} />
          </Card>
        </Col>
        <Col xs={24} lg={6}>
          <Card size="small" title="设备告警排行">
            <div ref={barRef} style={{ height: 280 }} />
          </Card>
        </Col>
      </Row>

      <Card size="small" title="告警记录" style={{ marginTop: 12 }}>
        <Table rowKey={(r) => `${r.time}_${r.equipmentNo}_${r.type}_${r.level}`} columns={columns} dataSource={tableData} pagination={{ pageSize: 10 }} />
      </Card>
    </Card>
  );
}